﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace CSMF
{
    public partial class SinaHandleSmallReturn : System.Web.UI.Page
    {
        private void GotoIndexPage()
        {
            Response.Redirect("index.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var errorCode = Request.QueryString["error_code"];
                if (!string.IsNullOrEmpty(errorCode) && errorCode == "21330")
                {
                    lblMsg.Text = "授权失败";
                }

                //get weibo user info
                var service = new SinaService();
                var code = Request.QueryString["code"];

                var weiboUserInfo = service.GetSinaWeiboUserInfo(code, service.GetSmallLoginOAuth());
                if (weiboUserInfo == null)

                {
                    lblMsg.Text = "授权失败";
                }
                else
                {

                    var webContext = new WebWorkContext();
                    var user = webContext.CurrentUser;


                    if (service.IsNewSinaWeiboUser(weiboUserInfo.id))
                    {
                        service.CreateWeiboUser(weiboUserInfo);

                        Response.Redirect("registerSmallSinaUser.aspx?weiboUser="+weiboUserInfo.id);

                      
                    }
                    else
                    {


                        service.UpdateWeiboUserToken(weiboUserInfo.id, weiboUserInfo.Token);



                        var userService = new UserService();
                        var csmfUser = userService.GetUserBySinaWeiboUserId(weiboUserInfo.id);

                        var authenticationService = new AuthenticationService();
                        authenticationService.SignIn(csmfUser, true);

                        lblMsg.Text = "您已经登录";

                       

                    }
                }



               
            }
            catch (Exception ex)
            {
                //ApplicationLog.Error("微博登录返回异常", e);
                //return Redirect("/login");
            }
           // return null;
        }

      
    }
}